<?php

namespace app\controller;

use support\Request;
use think\facade\Db;
class AqaraBaseController
{

    //不需要登录的接口
    protected $noNeedLogin = ['index','setAccesstoken'];
    //测试方法
    public function index()
    {
        // $a = $this->lmrefreshToken('e0ade3a995b55061401c3d11c1fbcdc4','130365293428389478436b66','K.1303652934594273280','xuh5ni4yvszjmmby84di9b3k01c4v4k9');
        return ['code'=>1];
    }
    //设置token信息
    public function setAccesstoken(Request $request){
        $user_id = 1;
        $Accesstoken = $request->post('Accesstoken','');
        $refreshToken = $request->post('refreshToken','');
        if(!$Accesstoken || !$refreshToken){
            return json(['code'=>0,'msg'=>'缺失Accesstoken或refreshToken']);
        }
        $check = Db::name('aqara_token')->where(['user_id'=>$user_id])->find();
        $data['user_id'] = $user_id;
        $data['Accesstoken'] = $Accesstoken;
        $data['refreshToken'] = $refreshToken;
        $data['expiretime'] = time();//存当前时间戳 获取token的时候会自动更新保证数据库时间的正确性
        if($check){
            //之前有过 直接更新
            $res = Db::name('aqara_token')->where(['id'=>$check['id']])->update($data);

        }else{
            $res = Db::name('aqara_token')->insert($data);
        }
        return json(['code'=>1,'msg'=>'设置成功','data'=>['Accesstoken'=>$Accesstoken,'refreshToken'=>$refreshToken]]);
    }
    //获取token
    public function getAccesstoken($user_id,$Appid,$Keyid,$appKey){
        //查询此人Accesstoken
        $token = Db::name('aqara_token')->where(['user_id'=>$user_id])->find();
        if(!$token){
            return ['code'=>0,'msg'=>'Accesstoken不存在'];
        }
        //检查是否过期 提前1天处理
        if($token['expiretime']<=time()+24*60*60){
            //刷新token
            $res = $this->lmrefreshToken($token['refreshToken'],$Appid,$Keyid,$appKey,$token['id']);
            if($res['code']==1){
                return ['code'=>1,'msg'=>'ok','data'=>$res['data']];
            }else{
                return ['code'=>0,'msg'=>$res['msg']];
            }
        }else{
            return ['code'=>1,'msg'=>'ok','data'=>$token['Accesstoken']];
        }
    }
    //刷新token
    public function lmrefreshToken($refreshToken,$Appid,$Keyid,$appKey,$tokenid){
        $header = $this->gethearder($Appid,$Keyid,$appKey);
        $url = 'https://open-cn.aqara.com/v3.0/open/api';
        $data['intent'] = 'config.auth.refreshToken';
        $data['data'] = ['refreshToken'=>$refreshToken];
        $result = $this->PostJson($url,$data,$header);
        if($result['code']==0){
            //修改数据库信息
            $ins['Accesstoken'] = $result['result']['accessToken'];
            $ins['refreshToken'] = $result['result']['refreshToken'];
            $ins['expiretime'] = time()+$result['result']['expiresIn'];
            $res = Db::name('aqara_token')->where(['id'=>$tokenid])->update($ins);
            if($res){
                return ['code'=>1,'msg'=>'ok','data'=>$ins['Accesstoken']];
            }else{
                return ['code'=>0,'msg'=>'更新失败'];
            }
        }else{
            return ['code'=>0,'msg'=>$result['message']];
        }
    }
    /*
     *  拼装header
        Accesstoken:绿米Accesstoken
     *  Appid:绿米平台项目ID 项目管理->详情
     *  Keyid:绿米平台密钥ID
     *  appkey:绿米平台项目密钥
     */
    public function getHearder($Appid,$Keyid,$appKey,$Accesstoken=''){
        // $appKey = 'xuh5ni4yvszjmmby84di9b3k01c4v4k9';
        
        $hearder = [
            'Appid'=>$Appid,
            'Keyid'=>$Keyid,
            'Nonce'=>time().rand(10000,99999),
            'Time'=>time()*1000
        ];
        if($Accesstoken){
            $hearder = [
                'Accesstoken'=>$Accesstoken,
                'Appid'=>$Appid,
                'Keyid'=>$Keyid,
                'Nonce'=>time().rand(10000,99999),
                'Time'=>time()*1000
            ];
        }
        $str = http_build_query($hearder);
        $str .= $appKey;
        //转小写
        $str = strtolower($str);
        $sign = md5($str);
        $hearder['Sign'] = $sign;
        return $hearder;
    }
    public function yinshechazuo($intent,$subjectId,$resourceId,$value,$Appid,$Keyid,$appKey,$Accesstoken=''){
        $header = $this->gethearder($Appid,$Keyid,$appKey,$Accesstoken);
        $url = 'https://open-cn.aqara.com/v3.0/open/api';
        // $data['intent'] = 'write.resource.device';
        $data['intent'] = $intent;
        $data['data'][] = [
            'subjectId'=>$subjectId,
            'resources'=>[[
                'resourceId'=>$resourceId,
                'value'=>$value,
            ]],
        ];
        $res = $this->PostJson($url,$data,$header);
        return $res;
    }
    //发送json请求函数
    public function PostJson($url, $data = NULL,$headers=[])
    {
        $curl = curl_init();
        $header =array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen(json_encode($data)),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        );
        if($headers){
            foreach($headers as $k=>$v){
                $header[] = $k.':'.$v;
            }
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            return 'data is null';
        }
        if (is_array($data)) {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT, 60); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return json_decode($res,true);
    }
}
